package com.web3.management.service;

import com.web3.management.dto.response.LoginResponse;
import com.web3.management.entity.User;
import com.web3.management.exception.BusinessException;
import com.web3.management.repository.UserRepository;
import com.web3.management.util.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 认证服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    /**
     * 用户登录
     */
    public LoginResponse login(String username, String password) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(username);
        return new LoginResponse(token, username);
    }

    /**
     * token刷新
     */
    public LoginResponse refreshToken(String token) {
        String username = jwtTokenUtil.getUsernameFromToken(token);
        if (username == null) {
            throw new BusinessException(401, "无效的Token");
        }
        Optional<User> userOptional = userRepository.findByUsernameAndEnabled(username, true);
        if (!userOptional.isPresent()) {
            throw new BusinessException(401, "用户不存在或已禁用");
        }
        String newToken = jwtTokenUtil.generateToken(username);
        return new LoginResponse(newToken, username);
    }

    /**
     * 获取当前登录用户
     */
    public UserDetails getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !(authentication.getPrincipal() instanceof UserDetails)) {
            throw new BusinessException(401, "未登录");
        }
        return (UserDetails) authentication.getPrincipal();
    }

    /**
     * 修改当前用户密码
     */
    public void changePassword(String currentPassword, String newPassword) {
        UserDetails currentUserDetails = getCurrentUser();
        String username = currentUserDetails.getUsername();

        User user = userRepository.findByUsernameAndEnabled(username, true)
                .orElseThrow(() -> new BusinessException(404, "用户不存在"));

        // 验证当前密码
        if (!passwordEncoder.matches(currentPassword, user.getPasswordHash())) {
            throw new BusinessException(400, "当前密码错误");
        }

        // 更新为新密码
        user.setPasswordHash(passwordEncoder.encode(newPassword));
        userRepository.save(user);
        log.info("用户密码修改成功: {}", username);
    }

    /**
     * 修改用户密码（管理员用）
     */
    public void updatePassword(Integer userId, String rawPassword) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        user.setPasswordHash(passwordEncoder.encode(rawPassword));
        userRepository.save(user);
        log.info("用户密码更新成功: {}", user.getUsername());
    }
}
